package work.base.designpattern.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

// 1. 定义接口
interface PersonService {
    void createPerson(String username);

    String getPersonById(int id);
}

// 2. 实现接口的目标类
class PersonServiceImpl implements PersonService {
    @Override
    public void createPerson(String username) {
        System.out.println("创建用户: " + username);
    }

    @Override
    public String getPersonById(int id) {
        System.out.println("获取用户ID: " + id);
        return "用户_" + id;
    }
}

// 3. 实现InvocationHandler接口
class LoggingHandler implements InvocationHandler {
    private final Object target; // 目标对象

    public LoggingHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 方法调用前的日志
        System.out.println("[日志] 调用方法: " + method.getName());
        if (args != null) {
            System.out.println("[日志] 参数: " + String.join(", ", java.util.Arrays.toString(args)));
        }

        // 调用目标对象的方法
        Object result = method.invoke(target, args);

        // 方法调用后的日志
        System.out.println("[日志] 方法返回: " + result);
        return result;
    }
}

// 4. 测试类
public class JdkDynamicProxy {
    public static void main(String[] args) {
        // 创建目标对象
        PersonService target = new PersonServiceImpl();

        // 创建InvocationHandler
        InvocationHandler handler = new LoggingHandler(target);

        // 创建代理对象
        PersonService proxy = (PersonService) Proxy.newProxyInstance(PersonService.class.getClassLoader(),
                new Class<?>[]{PersonService.class}, handler);

        // 通过代理对象调用方法
        proxy.createPerson("testPerson");
        String user = proxy.getPersonById(123);
        System.out.println("返回结果: " + user);
    }
}
